import os
import time
from flask import redirect, request, url_for
from backend.baseapp import app, db, tasks_manager
from backend.configs import get_config
from backend.routers import (
    bp_container_mgr,
    bp_login_mgr,
    set_login_manager,
    bp_dev_env_imgs,
    bp_host_machine_info,
    bp_snapshots,
    bp_background_tasks,
)
from backend.services import svc_host_machine_info

import argparse
import subprocess
import signal
import sys


parser = argparse.ArgumentParser(
    description="Run the application with optional Docker operator."
)
parser.add_argument(
    "--with-docker-operator",
    action="store_true",
    help="Start the Docker operator service.",
)
parser.add_argument(
    "--debug",
    action="store_true",
    help="Activate the hotreload feature.",
)
args = parser.parse_args()

app.register_blueprint(bp_background_tasks)
app.register_blueprint(bp_container_mgr)
app.register_blueprint(bp_login_mgr)
app.register_blueprint(bp_dev_env_imgs)
app.register_blueprint(bp_host_machine_info)
app.register_blueprint(bp_snapshots)

set_login_manager(app)


@app.route("/")
def root_redirect():
    return redirect(url_for("container_mgr.dashboard"))


def get_ssl_context():
    global sslify
    configs = get_config()
    if configs["nginx_ssl_used"]:
        base_path = os.path.join(
            os.path.dirname(__file__), "backend", "nginx_configs", "configs", "certs"
        )
        return (
            os.path.join(base_path, configs["nginx_cert_filename"]["pem"]),
            os.path.join(base_path, configs["nginx_cert_filename"]["key"]),
        )


if __name__ == "__main__":
    # 新增：根据命令行参数决定是否启动Docker operator
    docker_operator_process = None
    if args.with_docker_operator:
        assert args.debug is False, "Cannot use --debug with --with-docker-operator"
        print("Starting Docker operator service...")
        docker_operator_process = subprocess.Popen(
            ["python", "docker_operator.py"], stdout=sys.stdout, stderr=sys.stderr
        )

    with app.app_context():
        db.create_all()

        # 确保默认主机记录确实存在
        svc_host_machine_info.ensure_default_host_exists()

    print(app.url_map)
    print(get_config())
    kwargs = {}

    try:
        app.run(debug=args.debug, host="0.0.0.0", port=3640)
    except KeyboardInterrupt:
        print("\nShutting down the application...")
        if docker_operator_process:
            print("Terminating Docker operator service...")
            docker_operator_process.terminate()
            docker_operator_process.wait()
        sys.exit(0)
